<?php
namespace app\web\controller\admin;

use app\admin\library\AdminController;
use app\admin\library\User as adminUser;
use cubox\Cubox;
use app\web\library\PartPower;

class Article extends AdminController{
    public function onIndex(){

        $part_id = $this->get('part',$this->check()->type('int')->default(0));

        $partPower = new PartPower($this->app);
        if (!$partPower->inPart($part_id)){
            throw new \Exception('没有权限');
        }
        
        if ($part_id){
            $part = $this->model('Part');
            $data = $part->getId($part_id);
    
            if (!$data) throw new \Exception('没有找到该栏目');
            $this->set('part',$data);
            $this->pageTitle =$data['title'];
        }else{
            $this->pageTitle = '文章';
        }
       
        $article  = $this->model('Article');

        
        $this->set('articleStatusOption',$article->statusDefine());

        
        $this->pageIcon  = 'fa-file-text-o';
        $this->set('part_id',$part_id);
        
        return $this->display();
    }

    public function onList(){
        $this->power('web.article');
        $part_id = $this->post('part_id',$this->check('栏目')->type('int')->default(0));
        $page = $this->post('page',$this->check('页码')->type('int')->default(1));
        $status = $this->post('status',$this->check('状态')->type('string'));
        $keyword = $this->post('keyword',$this->check('关键字')->type('string')->default(''));


        $partPower = new PartPower($this->app);

        if (!$partPower->inPart($part_id)){
            throw new \Exception('没有权限');
        }


        $pageSize = 30;

        $part = $this->model('Part');

        $article = $this->model('Article');
        
        if ($part_id==0){
            if (!$partPower->partSuper()){
                $article->where('part_id','in',$partPower->getPartList());
            }
        }else{
            
            if ($page==1){
                $this->commonUse($part_id);
            }
            $article->where('part_id','in',$part->getKeyCollect($part_id));
        }
        
        if ($keyword){
            $article->where(['title','content','param'],'like','%'.$keyword.'%');
        }

        if ($status){
            $article->where('status',$status);
        }

        $list = $article->order('create_time','desc')->page($page,$pageSize)->getData();

        
        foreach($list as $k=>$v){
            $list[$k] =  $article->formate($v);
            unset($list[$k]['content']);
        }
        
        
        return ['list'=>$list,'total'=>$article->total,'count'=>$article->pageCount];

    }


    public function onEdit(){
        $this->power('web.article');
        $id = $this->get('article',$this->check('ID')->type('int'));
        $part_id = $this->get('part',$this->check('ID')->type('int'));
        
        if ($id){
            $article = $this->model('Article');
            $data = $article->getId($id);

            try{
                $param = json_decode($data['param'],true);
            }catch(\Exception $e){
                $param = [];
            }


            $part_id = $data['part_id'];
            $partPower = new PartPower($this->app);
            if (!$partPower->inPart($part_id)){
                throw new \Exception('没有权限');
            }

            $this->pageTitle = '编辑文章';

            $this->set('article',$data);
            $this->set('param',$param);
            
        }else{
            $this->pageTitle = '添加文章';
        }


        if ($part_id){
            $part = $this->model('Part');
            $partData = $part->getId($part_id);
            if (!$partData){
                throw new \Exception('没有找到该栏目');
            }
            $this->set('part_id',$part_id);
            $this->set('part_model_id',$partData['article_model_id']);
        }

        return $this->display();
    }


    public function onSave(){
        
        $this->power('web.article');
        $id = $this->post('article_id',$this->check('ID')->type('int'));
        $data['title'] =  $this->post('title',$this->check('title')->type('string')->required());
        $data['part_id'] =  $this->post('part_id',$this->check('栏目')->type('int')->required());
        $data['title_style'] = $this->post('title_style',$this->check()->type('string'));
        $data['content'] = $this->post('content',$this->check()->type('string'));
        $data['route'] = $this->post('route',$this->check()->type('string'));
        $data['route_type'] = $this->post('route_type',$this->check()->type('string'));
        $data['model_id'] = $this->post('model_id',$this->check()->type('int'));
        $data['template'] = $this->post('template',$this->check()->type('string'));
        if ($data['route_type']!='default'){
            if ($data['route']==''){
                throw new \Exception('路由不能为空');
            }
        }



        $partPower = new PartPower($this->app);
        if (!$partPower->inPart($data['part_id'])){
            throw new \Exception('没有权限');
        }

        $data['param'] = json_encode($this->post('param',[]));

        $article = $this->model('Article');
        if ($id){
            $data['update_time'] =  time();
            
            if ($article->updateId($id,$data)){
                $this->log('编辑文章', ['article_id'=>$id,'title'=>$data['title']]);

                $this->commonUse($data['part_id']);


                return true;
            }else{
                throw new \Exception('编辑文章失败');
            }
        }else{
            $data['create_time'] = time();
            $data['update_time'] = time();
            $data['status'] = 'new';
            $data['admin_user_id'] = adminUser::get('user_id');
            $data['admin_user_nick'] = adminUser::get('nickname');

            if ($article->insert($data)){
                $this->log('添加文章', ['article_id'=>$article->getInsertId(),'title'=>$data['title']]);
                $this->commonUse($data['part_id']);
                return true;
            }else{
                throw new \Exception('添加文章失败');
            }
        }
        
    }

    public function onDel(){
        $this->power('web.article');
        $id = $this->post('article_id',$this->check('ID')->type('int'));

        $article = $this->model('Article');

        $oldData  = $article->getId($id);
        $partPower = new PartPower($this->app);
        if (!$partPower->inPart($oldData['part_id'])){
            throw new \Exception('没有权限');
        }

        if ($article->deleteId($id)){

            $this->log('删除文章', ['article_id'=>$id,'title'=>$oldData['title']]);

            return true;
        }else{
            throw new \Exception('删除失败');
        }

    }


    private function commonUse($part_id){

        if ($part_id==0) return true;
        $admin =  Cubox::app('admin');

        $userKey = $admin->model('UserKey');

        $str =  $userKey->getValue(adminUser::get('user_id'),'web-part-common-use');

        $data =[];
        try{
            if ($str){
                $data = json_decode($str,true);
            }else{
                $data = [];
            }
        }catch(\Exception $e){
            $data = [];
        }

        $key = 'part_'.$part_id;
         
        if (isset($data[$key])){
            $data[$key]  ++ ;
        }else{
            $data[$key] = 1;
        }

        $userKey->setValue(adminUser::get('user_id'),'web-part-common-use',json_encode($data));
    }
}